package com.study.aidlsample.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteCallbackList;
import android.os.RemoteException;
import android.util.Log;

import androidx.annotation.Nullable;

import com.study.aidlsample.IMessageReceiver;
import com.study.aidlsample.IMessageSender;
import com.study.aidlsample.MainActivity;
import com.study.aidlsample.model.Message;

import java.util.Date;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 作者： zjf 10/8/20 3:40 PM
 * 参考：
 * 描述：
 */
public class RemoteService extends Service {

    //记录服务是否被销毁,AtomicBoolean为线程安全的布尔类型
    private AtomicBoolean isServiceDestroy = new AtomicBoolean(false);
    //RemoteCallbackList是专门用来管理多进程回调接口的集合
    private RemoteCallbackList<IMessageReceiver> callbackList = new RemoteCallbackList<>();
    /**
     * 拿到AIDL帮我们生成的Binder对象
     * 并且我们在AIDL定义的方法,在这里都进行了回调
     */
    IBinder iMessageSender = new IMessageSender.Stub() {
        @Override
        public void sendMessage(Message message) throws RemoteException {
            Log.e("RemoteService", message.toString());
        }

        @Override
        public void registerReceiveListener(IMessageReceiver messageReceiver) throws RemoteException {
            callbackList.register(messageReceiver);
        }

        @Override
        public void unregisterReceiveListener(IMessageReceiver messageReceiver) throws RemoteException {
            callbackList.unregister(messageReceiver);
        }
    };

    @Override
    public void onCreate() {
        super.onCreate();
        /**
         * 定义一个线程,执行异步任务
         */
        new Thread(new Task()).start();
    }

    @Override
    public void onDestroy() {
        isServiceDestroy.set(true);
        super.onDestroy();
    }

    /**
     * 实现Runnable接口,执行任务
     */
    class Task implements Runnable {

        @Override
        public void run() {
            //服务没被销毁就一直运行
            while (!isServiceDestroy.get()) {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Message message = new Message();
                message.setFrom(RemoteService.class.getName());
                message.setTo(MainActivity.class.getName());
                message.setContent(String.valueOf(new Date().getTime()));

                //开始遍历远程接口回调,执行完注意finishBroadcast()
                int receiverCount = callbackList.beginBroadcast();
                for (int i = 0; i < receiverCount; i++) {
                    try {
                        //调用信息回调
                        callbackList.getBroadcastItem(i).onMessageReceived(message);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }
                callbackList.finishBroadcast();
            }
        }
    }

    /**
     * 绑定服务回调接口
     */
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return iMessageSender;
    }
}
